<template>

  <view class="components-list tn-safe-area-inset-bottom">

    <!-- 顶部自定义导航 -->
    <tn-nav-bar fixed>列表</tn-nav-bar>
    <tn-nav-bar fixed backgroundColor="tn-main-gradient-orangeyellow">
      <span v-if="type == 0">喂奶</span>
      <span v-else-if="type == 1">辅食</span>
      <span v-else-if="type == 2">尿不湿</span>
    </tn-nav-bar>

    <!-- 页面内容 -->
    <view :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
      <demo-title leftIcon="" rightIcon="" v-for="(items, index) in baseList" :key="index">
        <view id="render-sub" class="sub-box">
          <tn-list-view :card="true" :customTitle="true" unlined="bottom">
            <template slot="title">
              <view class="custom-title" style="display: flex; flex-direction: column; align-items: flex-start;">
                <view class="date">{{ formatDate(index) }}</view>
                <view v-if="type != 2" class="total-quantity">
                  <text style="color: rgb(240, 147, 10);" class="tn-icon-like-fill tn-padding-right-xs tn-text-sm"></text>
                 <text class="tn-text-sm tn-color-gray tn-padding-top">总量: {{ items.reduce((sum, item) => sum + (item.quantity || 0), 0) }}{{type == 0 ? 'ml' : 'g'}}</text>
                </view>
                <!-- <tn-button  @click="cusRenderDom" class="tn-icon-share-square"></tn-button> -->
              </view>
            </template>
            <tn-swipe-action>
              <block v-for="item in items" :key="item.id">
                <tn-swipe-action-item :options="options3" :name="item.id" @click="onSwiperItemClick">
                  <tn-list-cell @click.native="openPopup(item)">
                    <span>{{ formatTime(item.createTime) }}</span>
                    <span style="padding-right: 10rpx;">{{ item.remark }}</span>
                    <text class="t-icon" :class="getColorClass()"></text>
                    <span v-if="type != 2" class="content">{{ item.quantity }}{{type == 0 ? 'ml' : 'g'}} </span>
                  </tn-list-cell>
                </tn-swipe-action-item>
              </block>
            </tn-swipe-action>
          </tn-list-view>
        </view>
      </demo-title>
      <tn-empty mode="data" v-if="Object.keys(baseList).length ==0"></tn-empty>
    </view>
    <view :style="{ paddingTop: vuex_custom_bar_height + 'px' }">
			<tn-toast ref="toast"></tn-toast>
		</view>

    <!-- popup -->
		<record-popup
			:show="show"
			:type="Number(type)"
      :editData="currentEditData"
			:mode="mode"
			:backgroundColor="backgroundColor"
			:width="width"
			:height="height"
			:borderRadius="23"
			:closeBtn="closeBtn"
			:closeBtnIcon="closeBtnIcon"
			:closeBtnPosition="closeBtnPosition"
			:maskCloseable="maskCloseable"
			@close="closedPopup"
			@save="save"
		/>

  </view>

</template>

<script>
import demoTitle from '@/libs/components/demo-title.vue'
import { HandleSQLite } from '@/util/handle_SQLite.js'
import { localSqliteApi } from '@/api/local_sqlite_api.js'
import { mapActions, mapState } from 'vuex';
import { base64ToPath } from '@/uni_modules/sp-html2canvas-render/utils/index.js'
export default {
  name: 'componentsList',
  components: { demoTitle },
  data() {
    return {
      Db: new HandleSQLite(localSqliteApi, 'main', 'table1'),
      type: 0,
      showListOptions: false,
      cellShowBorderLine: true,
      cellLongBorderLine: false,
      cellNoPaddingArrow: false,
      cellArrow: false,
      cellArrowRight: true,
      cellUnlined: false,
      cellLineLeft: true,
      cellLineRight: true,
      options3: [
        {
          text: '删除',
          icon: 'delete',
          style: {
            backgroundColor: '#E83A30'
          }
        }
      ],
      imagePath: '', // 保存生成的图片路径
      show: false,
			mode: 'bottom',
			backgroundColor: '',
			width: '80%',
			height: '65%',
			borderRadius: 23,
			closeBtn: true,
			closeBtnIcon: 'close',
			closeBtnPosition: 'top-right',
			maskCloseable: true,
      currentEditData: null
    }
  },
  onLoad: function (options) {
    this.type = options.type 
    this.select()
  },

  computed: {
    ...mapState(['listDatas', 'selectedTime']),
    baseList() {
      if (!this.listDatas) return {};
      return this.groupDataByDate(this.listDatas);
    }
  },
  watch: {
    cellShowBorderLine(val) {
      if (val) {
        this.cellUnlined = false
      } else {
        this.cellUnlined = true
      }
    },
    cellLongBorderLine(val) {
      if (val) {
        this.cellLineLeft = false
        this.cellLineRight = false
      } else {
        this.cellLineLeft = true
        this.cellLineRight = true
      }
    },
    cellNoPaddingArrow(val) {
      if (val) {
        this.cellArrowRight = false
      } else {
        this.cellArrowRight = true
      }
    }
  },
  methods: {
    ...mapActions(['getList']),
    formatDate(dateString) {
      const date = new Date(dateString);

      // 获取年份、月份和日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0');

      // 获取星期几
      const dayOfWeekMap = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const dayOfWeek = dayOfWeekMap[date.getDay()];

      // 返回格式化后的字符串
      return `${year}年${month}月${day}日 ${dayOfWeek}`;
    },
    formatTime(dateTimeString) {
      const date = new Date(dateTimeString.replace(/-/g, '/'));
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    onSwiperItemClick(e) {
      if (e.type === 'button') {
        this.Db.execute("delete", { "id": e.name })
        if (this.Db.state) {
          this.select()
        }

      }
    },
    select() {
      this.getList()
    },
    getColorClass() {
      const classArray = ["t-icon-naiping", "t-icon-ertongfushi", "t-icon-yingerzhiniaoku zhiniaokutext"]
      return classArray[this.type]

    },
    groupDataByDate(data) {
      const groupedData = data.reduce((acc, item) => {
        if (item.type != this.type) return acc;
        const date = item.createTime.split(' ')[0];
        if (!acc[date]) {
          acc[date] = [];
        }
        acc[date].push(item);
        return acc;
      }, {});

      const sortedData = Object.keys(groupedData)
        .sort((a, b) => new Date(b) - new Date(a))
        .reduce((acc, date) => {
          acc[date] = groupedData[date].sort((a, b) => {
            const timeA = new Date(a.createTime.replace(/-/g, '/')).getTime();
            const timeB = new Date(b.createTime.replace(/-/g, '/')).getTime();
            return timeA - timeB;
          });
          return acc;
        }, {});

      return sortedData;
    },
    save(data) {
      let selectedTime = this.selectedTime
			const now = new Date()
			if (new Date(this.selectedTime) > now) {
				this.$refs.toast.show({
					title: '选择的时间大于当前时间了 ',
					content: '',
					duration: 1500
				})
        return ;
			 }
    
			this.Db.execute("update", {
        "id": data.id,
				"context": {
					"createTime": selectedTime,
					"remark": data.remark,
					"quantity": data.value
				}
			})
			this.select()
			this.closedPopup()
		},
    closedPopup() {
      this.show = false
    },
    openPopup(item) {
      this.currentEditData = item
      // console.log('==== item :', item)
       this.show = true
    },
    // renderOver(e) {
    //     this.reviewBaseImg = e
    //     this.showDelayDom = true
    //     // console.log('==== renderOver :', e);
    //     base64ToPath(e).then((res) => {
    //   uni.share({
    //   	provider: "weixin",
    //   	scene: "WXSceneTimeline",
    //   	type: 2,
    //   	imageUrl: res,
    //   	success: function (res) {
    //   		console.log("success:" + JSON.stringify(res));
    //   	},
    //   	fail: function (err) {
    //   		console.log("fail:" + JSON.stringify(err));
    //   	}
    //   });
    //       console.log('==== base64ToPath :', res)
    //     })
    //   },
    //   cusRenderDom() {
    //     this.$refs.renderRef.h2cRenderDom()
    //   }

  }
}
</script>

<style lang="scss" scoped>
.zhiniaokutext {
  margin-bottom: -8rpx;
}

span {
  margin-left: 20rpx;
}

.components-list {
  background-color: $tn-bg-gray-color;
  min-height: 100vh;
}

.custom-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10rpx 20rpx;
}

.list__options {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.list {
  &__left {
    display: flex;
    align-items: center;
    justify-content: flex-start;

    &__icon,
    &__image {
      margin-right: 18rpx;
    }
  }

  &__right {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

.list-icon-text,
.list-image-text {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.list-image-text {
  .list {
    &__left {
      &__image {
        width: 20rpx;
        height: 20rpx;
      }
    }
  }
}

.message {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;

  &__left {
    width: 10%;
  }

  &__middle {
    width: 80%;
    padding-left: 20rpx;
    padding-right: 40rpx;
  }

  &__right {
    width: 10%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  &__name {
    font-size: 32rpx;
    margin-bottom: 8rpx;
  }

  &__content {
    font-size: 26rpx;
    color: #838383;
  }

  &__tips {
    &__icon {
      font-size: 36rpx;
      color: #AAAAAA;
    }
  }
}

.swipe-action__item {
  padding: 10rpx 20rpx;

  &__image {
    image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 20rpx;
    }
  }

  &__info {
    margin-left: 20rpx;

    &__title {
      font-size: 30rpx;
      font-weight: bold;
    }

    &__desc {
      margin-top: 5rpx;
      font-size: 22rpx;
      color: $tn-font-sub-color;
    }
  }
}
</style>
